﻿using System.Collections.Generic;
using System.IO;
using System;
using project1113.observer;
/// <summary>
/// 这个类用于读取配置文件 ，
/// 注意！！从文件里读取的默认是string类型，请自行判断数据类型并转化！--zyx
/// </summary>
namespace project1113.iniParser{

    public class IniParser
    {
        private readonly Dictionary<string, string> settings;
        IErrorObserver _observer;
        public IniParser(string filePath, IErrorObserver observer)
        {
            _observer = observer;
            settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            LoadIniFile(filePath);
        }

        private void LoadIniFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    foreach (var line in File.ReadAllLines(filePath))
                    {
                        // 忽略注释
                        if (string.IsNullOrWhiteSpace(line) || line.Trim().StartsWith("#") || line.Trim().StartsWith(";"))
                            continue;

                        var parts = line.Split('=');
                        if (parts.Length == 2)
                        {
                            var key = parts[0].Trim();
                            var value = parts[1].Trim();
                            settings[key] = value;
                        }
                    }
                }
                else
                {
                    throw new FileNotFoundException("找不到INI文件", filePath);
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                _observer.HandleError(ex.Message);
            }
        }
        /// <summary>
        /// 读取参数 返回的是可能为空的string类型，如果没有这个参数返回空
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string? GetSetting(string key)
        {
            if (settings.TryGetValue(key, out var value))
            {
                return value;
            }
            else
            {
                return null; // 未找到键
            }
        }

    }


    public class Item
    {
        public int ItemNum { get; set; }
    }

    public class Person
    {
        public string PersonName { get; set; }
    }

    public class Location
    {
        public int LocationNum { get; set; }
    }
    /// <summary>
    /// 读配置表的类
    /// </summary>
    public class ConfigFileReader
    {
        IErrorObserver _observer;
        private readonly Dictionary<string, Item> itemTable;
        private readonly Dictionary<string, Person> personTable;
        private readonly Dictionary<string, Location> locationTable;
        public ConfigFileReader(string filePath, IErrorObserver observer)
        {
            _observer = observer;
            itemTable = new Dictionary<string, Item>();
            personTable = new Dictionary<string, Person>();
            locationTable = new Dictionary<string, Location>();
            LoadConfigFile(filePath);
        }
        private void LoadConfigFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    string currentSection = "";
                    foreach (var line in File.ReadLines(filePath))
                    {
                        // 跳过空行
                        if (string.IsNullOrWhiteSpace(line) || line.Trim().StartsWith("#") || line.Trim().StartsWith(";"))
                            continue;
                        if (line.StartsWith("[") && line.EndsWith("]"))
                        {
                            // 新的配置部分
                            currentSection = line.Trim('[', ']');
                        }
                        else
                        {
                            // 键值对
                            var parts = line.Split(new char[] { '=' }, 2); // 将分割限制为2个部分
                            if (parts.Length == 2)
                            {
                                var key = parts[0].Trim();
                                var value = parts[1].Trim();

                                // 根据当前部分处理不同的表
                                switch (currentSection.ToUpper())
                                {
                                    case "ITEMTABLE":
                                        itemTable[key] = new Item { ItemNum = int.Parse(value) };
                                        break;

                                    case "PERSONTABLE":
                                        personTable[key] = new Person { PersonName = value };
                                        break;

                                    case "LOCATIONTABLE":
                                        locationTable[key] = new Location { LocationNum = int.Parse(value) };
                                        break;

                                    // 如果需要，为其他表添加更多的case

                                    default:
                                        // 如果需要，处理未识别的部分
                                        break;
                                }
                            }
                            else
                            {
                                // 记录或处理格式不正确的行
                                _observer.HandleError($"行格式无效: {line}");
                            }
                        }
                    }
                }
                else
                {
                    _observer.HandleError($"找不到配置文件:{filePath}");
                    throw new FileNotFoundException("找不到配置文件", filePath);

                }
            }
            catch (Exception ex)
            {
                _observer.HandleError(ex.Message);
            }
        }

        public Item GetItem(string key)
        {
            if (itemTable.TryGetValue(key, out var item))
            {
                return item;
            }
            else
            {
                return null; // Key not found in ItemTable
            }
        }

        public Person GetPerson(string key)
        {
            if (personTable.TryGetValue(key, out var person))
            {
                return person;
            }
            else
            {
                return null; // Key not found in PersonTable
            }
        }

        public Location GetLocation(string key)
        {
            if (locationTable.TryGetValue(key, out var location))
            {
                return location;
            }
            else
            {
                return null; // Key not found in LocationTable
            }
        }
    }
}
